package com.xbq.exceleditor.ui.filechooser.media

import android.content.Context
import android.provider.MediaStore
import android.text.TextUtils
import android.webkit.MimeTypeMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.*

object MediaStoreUtils {
    //扫描SD卡音乐文件
    suspend fun scanMusic(context: Context): List<MusicContentInfo>? = withContext(Dispatchers.IO) {
        val cr = context.contentResolver
        // 获取所有歌曲
        val cursor = cr?.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER
        )
        val list: MutableList<MusicContentInfo> = arrayListOf()
        cursor?.let {
            if (it.moveToFirst()) {
                do {
                    val music = MusicContentInfo()
                    val title =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
                    music.title = title
                    val singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
                    music.singer = singer
                    val album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM))
                    music.album = album
                    val size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE))
                    music.size = size
                    val duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
                    music.duration = duration.toLong()
                    val url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                    music.url = url
                    list.add(music)
                } while (it.moveToNext())
            }
        }

        list
    }

    suspend fun scanFileByType(
        context: Context,
        fileType: FileTypeEnum,
        keyword: String
    ): List<ContentResolveFile> = withContext(Dispatchers.IO) {
        val files: MutableList<ContentResolveFile> = ArrayList()
        val cr = context.contentResolver
        val SDCARD_VOLUMN_NAME = "external"
        val uri = MediaStore.Files.getContentUri(SDCARD_VOLUMN_NAME)
        //        String[] projection = null;
        val projection = arrayOf(
            MediaStore.Files.FileColumns.TITLE,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns.DATE_MODIFIED,
            MediaStore.Images.ImageColumns._ID,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATA
        )
        val sortOrder: String? = null // unordered
        val selectionMimeType = StringBuilder(MediaStore.Files.FileColumns.MIME_TYPE + " IN (")
        for (i in fileType.fileExtensions.indices) {
            if (i > 0) {
                selectionMimeType.append(",?")
            } else {
                selectionMimeType.append("?")
            }
        }
        selectionMimeType.append(")")
        val selectionArgsPdf: MutableList<String?> = ArrayList()
        for (ext in fileType.fileExtensions) {
            val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)
            selectionArgsPdf.add(mimeType)
        }
        if (!TextUtils.isEmpty(keyword)) {
            selectionMimeType.append(" and " + MediaStore.Files.FileColumns.TITLE + " like ?")
            selectionArgsPdf.add("%$keyword%")
        }
        val arr = selectionArgsPdf.toTypedArray()
        val allFiles =
            cr.query(uri, projection, selectionMimeType.toString(), arr, sortOrder)
        allFiles?.let {
            while (it.moveToNext()) {
                val fileName =
                    it.getString(it.getColumnIndex(MediaStore.Files.FileColumns.TITLE))
                val fileSize =
                    it.getLong(it.getColumnIndex(MediaStore.Files.FileColumns.SIZE))
                val fileTime =
                    it.getLong(it.getColumnIndex(MediaStore.Files.FileColumns.DATE_MODIFIED))
                val fileUri = MediaStore.Files.getContentUri(
                    SDCARD_VOLUMN_NAME,
                    it.getInt(it.getColumnIndex(MediaStore.Images.ImageColumns._ID))
                        .toLong()
                )
                val mimetype =
                    it.getString(it.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE))
                val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimetype)
                val filepath =
                    it.getString(it.getColumnIndex(MediaStore.Files.FileColumns.DATA))

//            Uri imageUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                    allPdfFiles.getInt(allPdfFiles.getColumnIndex(MediaStore.Images.ImageColumns._ID)));
                val file = ContentResolveFile()
                    .setFileName(fileName)
                    .setFilePath(filepath)
                    .setFileSize(fileSize)
                    .setFileTime(fileTime)
                    .setUri(fileUri)
                    .setFileExtension(".$ext")
                files.add(file)
            }
        }

        files
    }

}